﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Miao.UI
{
    /// <summary>
    /// 拥有矩形局限的拖拽
    /// </summary>
    public class RestrictedRectDrag : DragAndDrop
    {
        [Tooltip("额外的Rect大小")]
        public Rect AdditionalRect;
        [Tooltip("拖拽局限")]
        public RectTransform RestrictedRect; 

        public override void OnDrag(PointerEventData eventData)
        {
            base.OnDrag(eventData);
            ClampToWindow();
        }

        public void ClampToWindow()
        {
            Vector3 pos = rectTransform.localPosition;
            Vector3 minPosition = RestrictedRect.rect.min - rectTransform.rect.min;   //矩形(2D)左下角坐标相对差
            Vector3 maxPosition = RestrictedRect.rect.max - rectTransform.rect.max;   //矩形(2D)右上角坐标相对差                                                                                           //在min与max之间取值给panelRectTransform.localPosition
            pos.x = Mathf.Clamp(rectTransform.localPosition.x, minPosition.x, maxPosition.x);
            pos.y = Mathf.Clamp(rectTransform.localPosition.y, minPosition.y, maxPosition.y);
            rectTransform.localPosition = pos;//最终赋值
        }
    }
}

